import React, {useState} from "react";
import {
    Alert,
    Dimensions,
    Image,
    ScrollView,
    StatusBar,
    StyleSheet,
    Text,
    TextInput,
    ToastAndroid,
    TouchableOpacity,
    View,
} from "react-native";
import type {NativeStackScreenProps} from "@react-navigation/native-stack";
import {RootStackParamList} from "../../../App";
import LinearGradient from "react-native-linear-gradient";
import {AuthApi} from "@/api/auth.ts";
import Icon from "react-native-vector-icons/Ionicons";
import {useAuth} from "./hook/useAuth.ts";
import {
    Controller,
    FormProvider,
    useForm,
    useFormContext,
} from "react-hook-form";

type Props = NativeStackScreenProps<RootStackParamList, "Login">;

const PasswordForm = () => {
    const {
        control,
        formState: {errors},
    } = useFormContext(); // 从 Provider 获取 context
    const [isPasswordSecure, setIsPasswordSecure] = useState(true);
    return (
        <>
            <Text style={styles.label}>用户名</Text>
            <Controller
                control={control}
                name="username"
                render={({field: {onChange, value}}) => (
                    <TextInput
                        style={styles.input}
                        underlineColorAndroid="transparent"
                        placeholder=""
                        value={value}
                        onChangeText={onChange}
                        autoCapitalize="none"
                    />
                )}
            />
            {errors["username"] && (
                <Text>{(errors["username"] as any).message}</Text>
            )}

            <Text style={styles.label}>密码</Text>
            <View style={styles.passwordContainer}>
                <Controller
                    control={control}
                    name="password"
                    render={({field: {onChange, value}}) => (
                        <TextInput
                            style={styles.passwordInput}
                            placeholder=""
                            value={value}
                            onChangeText={onChange}
                            autoCapitalize="none"
                            underlineColorAndroid="transparent"
                            secureTextEntry={isPasswordSecure}
                        />
                    )}
                />
                <TouchableOpacity
                    onPress={() => setIsPasswordSecure(!isPasswordSecure)}>
                    <Text style={{color: "#1e90ff"}}>
                        {isPasswordSecure ? (
                            <Icon name="eye-off" size={24} color="black" />
                        ) : (
                            <Icon name="eye" size={24} color="black" />
                        )}
                    </Text>
                </TouchableOpacity>
                {errors["password"] && (
                    <Text>{(errors["password"] as any).message}</Text>
                )}
            </View>
        </>
    );
};

const SmsForm = ({onSendCode}: {onSendCode: () => void}) => {
    const {
        control,
        formState: {errors},
    } = useFormContext(); // 从 Provider 获取 context
    return (
        <>
            <Text style={styles.label}>手机号</Text>
            <Controller
                control={control}
                name="phone"
                render={({field: {onChange, value}}) => (
                    <TextInput
                        style={styles.input}
                        placeholder=""
                        value={value}
                        onChangeText={onChange}
                        keyboardType="phone-pad"
                    />
                )}
            />
            <Text style={styles.label}>验证码</Text>
            <View style={styles.codeInputContainer}>
                <Controller
                    control={control}
                    name="code"
                    render={({field: {onChange, value}}) => (
                        <TextInput
                            style={styles.codeInput}
                            placeholder=""
                            value={value}
                            onChangeText={onChange}
                            keyboardType="numeric"
                        />
                    )}
                />
                <TouchableOpacity
                    style={{
                        backgroundColor: "#1e90ff",
                        paddingVertical: 15,
                        borderRadius: 30,
                        alignItems: "center",
                        width: "40%",
                    }}
                    onPress={onSendCode}>
                    <Text
                        style={{
                            color: "#fff",
                            fontSize: 16,
                            fontWeight: "bold",
                        }}>
                        获取验证码
                    </Text>
                </TouchableOpacity>
            </View>
        </>
    );
};

const LoginScreen = ({navigation}: Props) => {
    const [loginMethod, setLoginMethod] = useState<"password" | "sms">(
        "password",
    );

    const [isAgreementChecked, setIsAgreementChecked] = useState(false);

    const {login, isLoading, error} = useAuth(navigation);

    const passwordFormMethods = useForm();
    const smsFormMethods = useForm();
    const onPasswordSubmit = (data: any) => login(data, "password");
    const onSmsSubmit = (data: any) => login(data, "sms");

    const phone = smsFormMethods.watch("phone");
    const sendSMScode = async () => {
        ToastAndroid.show("验证码已发送", ToastAndroid.SHORT);
        const res = await AuthApi.sendSmsCode({mobile: phone, scene: 1});
        console.log(res);
    };

    return (
        <ScrollView style={styles.container} contentContainerStyle={{}}>
            <StatusBar backgroundColor="#2498F7" />
            <LinearGradient
                locations={[0.55, 1]}
                colors={["#2498F7", "transparent"]}
                style={styles.background}
            />
            <View
                style={{
                    justifyContent: "space-between",
                    display: "flex",
                    minHeight: Dimensions.get("window").height,
                }}>
                <View style={styles.content}>
                    <Image
                        width={Dimensions.get("window").width * 0.7}
                        source={require("../../assets/images/v2_szdchi.png")}
                        style={styles.logo}
                    />
                    <Text style={styles.title}>文件管理系统</Text>
                    <View style={styles.form}>
                        <View style={styles.switchContainer}>
                            <TouchableOpacity
                                onPress={() => setLoginMethod("sms")}>
                                <Text
                                    style={[
                                        styles.switchText,
                                        loginMethod === "sms" &&
                                            styles.switchTextActive,
                                    ]}>
                                    短信登录
                                </Text>
                            </TouchableOpacity>
                            <View
                                style={{
                                    height: "60%",
                                    width: 1,
                                    backgroundColor: "#ccc",
                                    // 放一条竖线
                                }}
                            />
                            <TouchableOpacity
                                onPress={() => setLoginMethod("password")}>
                                <Text
                                    style={[
                                        styles.switchText,
                                        loginMethod === "password" &&
                                            styles.switchTextActive,
                                    ]}>
                                    密码登录
                                </Text>
                            </TouchableOpacity>
                        </View>
                        {loginMethod === "password" ? (
                            <FormProvider {...passwordFormMethods}>
                                <PasswordForm />
                                {error && (
                                    <Text style={styles.errorText}>
                                        {error}
                                    </Text>
                                )}
                                <TouchableOpacity
                                    disabled={!isAgreementChecked || isLoading}
                                    style={[
                                        styles.loginButton,
                                        (!isAgreementChecked || isLoading) &&
                                            styles.disabledButton,
                                    ]}
                                    onPress={passwordFormMethods.handleSubmit(
                                        onPasswordSubmit,
                                    )}>
                                    <Text style={styles.loginButtonText}>
                                        {isLoading ? "登录中..." : "登录"}
                                    </Text>
                                </TouchableOpacity>
                            </FormProvider>
                        ) : (
                            <FormProvider {...smsFormMethods}>
                                <SmsForm onSendCode={sendSMScode} />
                                {error && (
                                    <Text style={styles.errorText}>
                                        {error}
                                    </Text>
                                )}
                                <TouchableOpacity
                                    disabled={!isAgreementChecked || isLoading}
                                    style={[
                                        styles.loginButton,
                                        (!isAgreementChecked || isLoading) &&
                                            styles.disabledButton,
                                    ]}
                                    onPress={smsFormMethods.handleSubmit(
                                        onSmsSubmit,
                                    )}>
                                    <Text style={styles.loginButtonText}>
                                        {isLoading ? "登录中..." : "登录"}
                                    </Text>
                                </TouchableOpacity>
                            </FormProvider>
                        )}
                    </View>

                    <View style={styles.agreementContainer}>
                        <TouchableOpacity
                            style={styles.checkbox}
                            onPress={() =>
                                setIsAgreementChecked(!isAgreementChecked)
                            }>
                            {isAgreementChecked && (
                                <View style={styles.checkmark} />
                            )}
                        </TouchableOpacity>
                        <Text style={styles.agreementText}>
                            我已阅读并同意
                            <Text
                                style={styles.linkText}
                                onPress={() =>
                                    Alert.alert(
                                        "用户协议",
                                        "这里是用户协议内容...",
                                    )
                                }>
                                《用户协议》
                            </Text>
                        </Text>
                    </View>
                </View>
                <View style={styles.footer}>
                    <Text style={styles.footerText}>
                        ——————— 第三方登录 ———————
                    </Text>
                    <Image
                        source={require("../../assets/images/wechat2.png")}
                        style={{
                            width: 50,
                            height: 50,
                            borderRadius: 20,
                            marginTop: 10,
                        }}
                    />
                </View>
            </View>
        </ScrollView>
    );
};

const styles = StyleSheet.create({
    container: {
        width: "100%",
        minHeight: "100%",
        height: Dimensions.get("window").height,
    },
    background: {
        position: "absolute",
        left: 0,
        right: 0,
        top: 0,
        height: Dimensions.get("window").height * 0.5,
    },
    content: {
        width: "100%",
        paddingHorizontal: "3%",
    },
    title: {
        fontSize: 28,
        fontWeight: 800,
        textAlign: "center",
        marginBottom: "3.5%",
        color: "#fff",
    },
    logo: {
        alignSelf: "center",
        marginTop: "23%",
        marginBottom: "7%",
    },
    input: {
        height: 50,
        lineHeight: 20,
        borderRadius: 30,
        marginBottom: 20,
        paddingHorizontal: "4.5%",
        backgroundColor: "rgba(0,96,177,0.05)",
        textAlignVertical: "center",
    },
    label: {
        fontSize: 18,
        fontWeight: "bold",
        marginBottom: "3%",
    },
    switchContainer: {
        flexDirection: "row",
        justifyContent: "center",
        marginBottom: "6%",
    },
    switchText: {
        fontSize: 18,
        color: "grey",
        marginHorizontal: 55,
        paddingBottom: "1.5%",
    },
    switchTextActive: {
        color: "#1e90ff",
        borderBottomWidth: 2,
        borderBottomColor: "#1e90ff",
    },
    codeInputContainer: {
        flexDirection: "row",
        alignItems: "center",
        justifyContent: "space-between",
        marginBottom: "6%",
    },
    codeInput: {
        height: "90%",
        borderRadius: 30,
        paddingHorizontal: "4.5%",
        backgroundColor: "rgba(0,96,177,0.05)",
        flex: 1, // 占据更多空间
        marginRight: "3%",
        textAlignVertical: "center",
    },
    form: {
        marginHorizontal: "3%",
        borderRadius: 30,
        backgroundColor: "#fff",
        padding: "5%",
        zIndex: 999,
    },
    disabledButton: {
        backgroundColor: "#ccc", // 一个通用的灰色，表示禁用
    },
    agreementContainer: {
        flexDirection: "row",
        alignItems: "center",
        justifyContent: "center",
        paddingHorizontal: "3%", // 保证内容不会贴边
        marginTop: 10,
    },
    checkbox: {
        width: 24,
        height: 24,
        borderWidth: 1,
        borderColor: "#999",
        borderRadius: 1,
        marginRight: "2%",
        justifyContent: "center",
        alignItems: "center",
    },
    checkmark: {
        width: 15,
        height: 15,
        backgroundColor: "#1e90ff",
        borderRadius: 2,
    },
    agreementText: {
        fontSize: 14,
        color: "grey",
    },
    linkText: {
        color: "#1e90ff",
    },
    footer: {
        flexDirection: "column",
        alignItems: "center",
        justifyContent: "center",
        marginVertical: 15,
    },
    footerText: {
        fontSize: 14,
        color: "grey",
    },
    passwordContainer: {
        flexDirection: "row",
        alignItems: "center",
        height: 50,
        borderRadius: 30,
        paddingHorizontal: "4.5%",
        marginBottom: 20,
        backgroundColor: "rgba(0,96,177,0.05)",
    },
    passwordInput: {
        flex: 1,
        color: "#000",
        height: "100%",
    },
    loginButton: {
        marginTop: 20,
        backgroundColor: "#1e90ff",
        paddingVertical: 15,
        borderRadius: 30,
        alignItems: "center",
        width: "100%",
    },
    loginButtonText: {
        color: "#fff",
        fontSize: 16,
        fontWeight: "bold",
    },
    errorText: {
        color: "red",
        textAlign: "center",
        marginBottom: 10,
    },
});

export default LoginScreen;
